package com.ihighest.app.infox.adapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.activity.InformationalContentActivity;

/**
 * 相关阅读数据适配器
 * 
 * @author Vity Created at 2015-10-22 上午12:26:33
 * @version 1.0
 */
public class RelatedReadingListViewAdapter extends BaseAdapter {
	private static final String TAG = "RelatedReadingListViewAdapter";
	Context context;
	JSONArray array;
	LayoutInflater inflater;

	public RelatedReadingListViewAdapter(Context context) {
		this.context = context;
		this.inflater = LayoutInflater.from(context);
	}

	public void setDatas(JSONArray jsonArray) {
		this.array = jsonArray;
	}

	public void appendDatas(JSONArray jsonArray) {
		try {
			this.array = AppKit.joinJSONArray(array, jsonArray);
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}
	}

	@Override
	public int getCount() {
		return array == null ? 0 : array.length();
	}

	@Override
	public Object getItem(int arg0) {
		return arg0;
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@SuppressLint("InflateParams")
	@Override
	public View getView(final int position, View convertView, ViewGroup arg2) {
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.infox_related_reading_listview_item, null);
			holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		try {
			JSONObject json = array.getJSONObject(position);
			holder.tv_title.setText(json.getString("title"));
			holder.tv_title.setTag(json.getString("id"));
		} catch (Exception ex) {
			Log.e(TAG, ex.getMessage(), ex);
		}
		// 点击事件
		holder.tv_title.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(context, InformationalContentActivity.class);
				intent.putExtra("newsId", (String) arg0.getTag());
				context.startActivity(intent);
			}
		});
		return convertView;
	}

	class ViewHolder {

		TextView tv_title;
	}
}
